package com.fenghongzhang.day015;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private ListView lv;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private Button pause;
    private Button stop;
    private Button restart;
    private Button pre;
    private Button next;

    private Timer timer;


    //当前播放下标的索引
    private int index;
    private SeekBar seekbar;

    private List<Music> music;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //最大值, 进度值.
        seekbar = (SeekBar) findViewById(R.id.seekbar);

        lv = (ListView) findViewById(R.id.lv);

        //shift + alt/ ctrl + shang xia
        pause = (Button) findViewById(R.id.pause);
        stop = (Button) findViewById(R.id.stop);
        restart = (Button) findViewById(R.id.restart);
        pre = (Button) findViewById(R.id.pre);
        next = (Button) findViewById(R.id.next);



        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.pause();
            }
        });

        restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.stop();
            }
        });

        //上一首
        pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index--;
                if (index <= 0 ){
                    index = 0;
                }
                play(index);
            }
        });

        //下一首
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playNext();
            }
        });

        //点击- > 播放
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                //播放重置
                play(position);
            }
        });


        //判断版本 //22
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
        }else{
            music = MusicUtil.getMusic(this);
            //适配器
            MusicAdapter musicAdapter = new MusicAdapter(this, music);
            lv.setAdapter(musicAdapter);
        }




        //
        /**
         * 数据源的来源 -> sd卡
         * 1,清单授权
         * 2,动态授权
         * 3,uri
         * 4,字段
         * 5,注意: 添加文件,重启手机.
         *
         */
//        MusicAdapter musicAdapter = new MusicAdapter(this,);

    }

    private void playNext() {
        index++;
        if(index > music.size()-1){
            index = 0;
        }
        play(index);
    }

    //control+alt +m
    private void play(int position) {
        if(timer != null){
            timer.cancel();
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(music.get(position).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                    seekbar.setMax(mediaPlayer.getDuration());//最大值
                }
            });

            //播放错误时候回调
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    //下一首
                    playNext();
                    return true;
                }
            });

            //播放完成的时候回调
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //下一首
                    playNext();
                }
            });

            //

            //用定时器,每秒更新精度
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    seekbar.setProgress(mediaPlayer.getCurrentPosition());//每秒更新进度.
                }
            },0,1000);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            music = MusicUtil.getMusic(this);
            //适配器
            MusicAdapter musicAdapter = new MusicAdapter(this, music);
            lv.setAdapter(musicAdapter);

        }else{
//            finish();
        }
    }
}
